package com.algo.GA;

import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: guoxing
 * @Email: gx_study2022@163.com
 * @Description: 个体类，包括了个体本身、他的适应度值以及对比的方法
 * @Date: 2024/6/3 15:28
 * @ClassName: Individual
 **/
@Data
@ToString
public class Individual implements Comparable<Individual> {

    //个体本身
    private List<Integer> individual;
    //适应度值
    private double fitness;
    //帮助值 十进制的值
    private double shijinzhi;
    public List<Integer> getIndividual() {
        return individual;
    }
    public void setIndividual(List<Integer> individual) {
        this.individual = individual;
        this.setFitness();
    }
    public double getFitness() {
        return fitness;
    }
    public Individual() {}
    public void setFitness() {
        double fitnessInt=binaryListToDecimal(this.individual);
        double fitness=fitnessInt/Param.MAX*Param.FW;
        this.shijinzhi=fitness;
//        this.fitness=2*fitness;
//        this.fitness=-fitness;
//        this.fitness = 3 * Math.pow(fitness, 5) + Math.sin(fitness) - Math.cos(2 * fitness) + Math.log10(fitness) - 4 * Math.pow(fitness, 2);
        this.fitness = Math.pow(fitness, 4) - 2 * Math.pow(fitness, 3) + 3 * Math.pow(fitness, 2) - 4 * fitness + 5; ;
    }


    /**
     * @Description 二进制列表转为十进制浮点型方法
     * @author guoxing
     * @date 2024/6/11 19:57
     * @param binaryList 待转换的二进制列表
     * @return int 转换结束的十进制参数
     */
    public static int binaryListToDecimal(List<Integer> binaryList) {
        int decimalNum = 0;
        for (int i = 0; i < binaryList.size(); i++) {
            int bit = binaryList.get(i);
            // 注意这里是从右到左，所以幂次是 binaryList.size() - 1 - i
            decimalNum += bit * (int) Math.pow(2, binaryList.size() - 1 - i);
        }
        return decimalNum;
    }




    public Individual(double fitness) {
        this.fitness=2*fitness;
//        this.fitness = Math.pow(fitness, 4) + 2 * Math.pow(fitness, 3) + 3 * Math.pow(fitness, 2) + 4 * fitness + 5; ;

    }

    /**
     * @Description 对比方法，会返回适应度较大的个体
     * 使用 Collections.sort(List<Individual> individuals) 即可按照适应度值进行升序排序
     * @author guoxing
     * @date 2024/6/11 19:28
     * @param other 待对比的个体
     * @return int
     */
    @Override
    public int compareTo(Individual other) {
        return Double.compare(this.getFitness(), other.getFitness());
    }


    public static void main(String[] args) {
        int fitness=10;
        double x=Math.pow(fitness, 4) - 2 * Math.pow(fitness, 3) + 3 * Math.pow(fitness, 2) - 4 * fitness + 5;
        System.out.println(x);
    }
}
